import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import { Icon } from '../icon';
import { Spinner } from '../spinner';
import { Fade } from '../fade';

export interface IToastProps {
  onClick?: React.MouseEventHandler;
  children?: React.ReactNode;
  icon?: string;
  color?: string;
  loading?: boolean;
  className?: string;
  style?: React.CSSProperties;
}

// 封装通用toast函数
const toastFactory = (iconType?: string, iconColor?: string) => (text: string, duration?: number) => {
  const ele = document.createElement('div');
  document.body.appendChild(ele);
  (iconType === undefined && iconColor === undefined) ? ReactDOM.render(
    <Toast loading>{text}</Toast>, ele) : ReactDOM.render(<Toast icon={iconType} color={iconColor}>{text}</Toast>, ele);
  const hide = () => {
    Toast.hide();
    setTimeout(() => {
      document.body.removeChild(ele);
    }, 1000);
  };
  if (duration) {
    setTimeout(() => {
      hide();
    }, duration);
  }
  return { hide };
};

interface IToastState {
  visible: boolean;
}

export class Toast extends React.Component<IToastProps, IToastState> {
  public static propTypes = {
    children: PropTypes.node,
    icon: PropTypes.string,
    color: PropTypes.string,
    className: PropTypes.string,
    style: PropTypes.object,
  };

  // 导出函数
  public static success = toastFactory('check-circle', '#43b52c');
  public static warn = toastFactory('warn-triangle', '#ffa126');
  public static error = toastFactory('close-solid', '#e22e33');
  public static loading = toastFactory();
  public static hide: () => void;

  constructor(props: IToastProps) {
    super(props);
    this.state = {
      visible: true,
    };
    Toast.hide = this.hide.bind(this);
  }
  public hide() {
    this.setState({ visible: false });
  }

  public render() {
    return (
      <Fade active={this.state.visible === undefined ? true : this.state.visible}
        className={classNames('br-toast', this.props.className)} style={this.props.style}>
        <div className="br-toast__body" >
          {this.props.icon ? <Icon className="br-toast__icon"
            type={this.props.icon} color={this.props.color}> </Icon>
            : null}
          {this.props.loading ? <Spinner className="br-toast__gifIcon" />
            : null}
          <div className="br-toast__content" >{this.props.children}</div>
        </div>
      </Fade>
    );
  }
}
